package com.ruoyi.web.websocket;

import com.alibaba.dashscope.aigc.generation.GenerationOutput;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.framework.websocket.WebSocketServer;
import com.ruoyi.system.service.IMyMessageService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.domain.MyMessage;
import com.ruoyi.web.service.ChatService;
import com.ruoyi.web.utils.UserMsgUtil;
import io.swagger.annotations.Api;
import org.apache.poi.ss.formula.functions.Now;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;

import javax.websocket.Session;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/wx")
public class ChatController {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ChatService chatService;
    @Autowired
    private IMyMessageService myMessageService;


    /**
     * 接收发来的消息，处理后发送到指定用户
     *
     * @param map
     * @return
     * @throws IOException
     */
    @PostMapping("/chat")
    public AjaxResult chat(@RequestBody Map<String, Object> map) throws IOException {
        String friendId = (String) map.get("friendId");
        System.err.println(friendId);
        Session session = WebSocketServer.USER_SESSIONS.get(friendId);
        if (session != null) {
            String message = (String) map.get("message");
            // 构建符合客户端期待的数据格式
            JSONObject jsonData = new JSONObject();
            jsonData.put("fromName", "other"); // 根据实际情况填充
            jsonData.put("message", message);
            session.getBasicRemote().sendText(jsonData.toString());
//            session.getBasicRemote().sendText(message);
        }
        return AjaxResult.success();
    }

    /**
     * 获取userId
     *
     * @return
     */
    @GetMapping("/chat/user")
    public AjaxResult getUser(SysUser sysUser) {
        // friend
        Long userId = sysUser.getUserId();// friendId
        SysUser friend = userService.selectUserById(userId);
        String friendAvatar = UserMsgUtil.subAvatar(friend.getAvatar());
        // 当前用户 user
        if (UserMsgUtil.getUserId() != null) {
            SysUser user = userService.selectUserById(UserMsgUtil.getUserId());
            String userAvatar = UserMsgUtil.subAvatar(user.getAvatar());

            // 构建返回的Map
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("userId", UserMsgUtil.getUserId());
            resultMap.put("userAvatar", userAvatar);
            resultMap.put("friendId", friend.getUserId());
            resultMap.put("friendAvatar", friendAvatar);
            return AjaxResult.success(resultMap);
        }
        return AjaxResult.success();
    }

    /**
     * 与gpt对话
     *
     * @return
     */
    @PostMapping("/chat/gpt")
    public AjaxResult chatWithGpt(@RequestBody MyMessage myMessage) {
        myMessage.setMsgType(2l);
        String input = myMessage.getInput();
        try {
            if (chatService.getMessage(input) != null) {
                GenerationResult result = chatService.getMessage(input);
                List<GenerationOutput.Choice> list = result.getOutput().getChoices();
                String content = list.get(0).getMessage().getContent();
                HashMap<Object, Object> map = new HashMap<>();
                map.put("content",content);
                return AjaxResult.success(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success();
    }
}
